package com.egg.ylt.fragment;

import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.egg.ylt.R;
import com.egg.ylt.Utils.GlideRoundTransform;
import com.egg.ylt.activity.ACT_NewsDetails;
import com.egg.ylt.activity.ACT_VideoPlaying;
import com.egg.ylt.pojo.BannerDataEntity;
import com.egg.ylt.pojo.BannerEntity;
import com.egg.ylt.pojo.MessageRecommendEntity;
import com.egg.ylt.presenter.impl.FindPresenterImpl;
import com.egg.ylt.view.IFindView;
import com.egg.ylt.widget.NewsScrollview;
import com.facebook.drawee.view.SimpleDraweeView;
import com.yonyou.framework.library.base.BaseFragment;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.CommonUtils;
import com.yonyou.framework.library.common.utils.ListUtil;
import com.yonyou.framework.library.common.utils.ScreenUtil;
import com.yonyou.framework.library.common.utils.StringUtil;
import com.yonyou.framework.library.eventbus.EventCenter;
import com.yonyou.framework.library.widgets.xbanner.XBanner;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sichaoqi on 2018/8/23.
 */

public class FRA_Find extends BaseFragment<FindPresenterImpl> implements IFindView {

    private static final int ITEM_SWIM = 0;
    private static final int ITEM_RECOVERY = 1;
    private static final int ITEM_BABY = 2;

    @BindView(R.id.rl_include_title)
    RelativeLayout rlIncludeTitle;
    @BindView(R.id.ll_recommend)
    LinearLayout llRecommend;
    @BindView(R.id.include_iv_back)
    ImageView ivBack;
    @BindView(R.id.include_tv_title)
    TextView tvTitle;
    @BindView(R.id.include_tv_right)
    TextView tvRight;

    @BindView(R.id.refresh_find)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.ll_news_view)
    LinearLayout llNewsView;
    @BindView(R.id.sv_content)
    NewsScrollview svContent;
    @BindView(R.id.ll_recommend_item1)
    LinearLayout llRecommendItem1;


    //内部tab

    @BindView(R.id.tv_news_swim)
    TextView tvNewsSwim;
    @BindView(R.id.line_news_swim)
    View lineNewsSwim;
    @BindView(R.id.tv_news_recovery)
    TextView tvNewsRecovery;
    @BindView(R.id.line_news_recovery)
    View lineNewsRecovery;
    @BindView(R.id.tv_news_baby)
    TextView tvNewsBaby;
    @BindView(R.id.line_news_baby)
    View lineNewsBaby;
    @BindView(R.id.banner)
    XBanner mBanner;


    //优惠信息
    @BindView(R.id.iv_re1_image)
    ImageView ivRe1Image;
    @BindView(R.id.tv_re1_title)
    TextView tvRe1Title;
    @BindView(R.id.tv_re1_des)
    TextView tvRe1Des;

    @BindView(R.id.ll_recommend_item)
    LinearLayout llRecommendItem;


    private FRA_NewsItem fraSwim;
    private FRA_NewsItem fraRecovery;
    private FRA_NewsItem fraBaby;

    //fragment对象
    private Fragment currentFragment;


    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    protected void onFirstUserVisible() {

    }

    @Override
    protected void onUserVisible() {

    }

    @Override
    protected void onUserInvisible() {

    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void initViewsAndEvents() {
        //动态设置沉浸式状态栏的高度
        int statusBarHeight = ScreenUtil.getStatusBarHeight(mContext);
        rlIncludeTitle.setPadding(0, statusBarHeight, 0, rlIncludeTitle.getPaddingBottom());
//        llTopView.setVisibility(View.GONE);
        ivBack.setVisibility(View.GONE);
        tvTitle.setText("发现");
        tvRight.setVisibility(View.GONE);

        ViewGroup.LayoutParams params = mBanner.getLayoutParams();
        params.height = ScreenUtil.getScreenWidth(getActivity()) / 2;
        mBanner.setLayoutParams(params);
        mBanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                //此处适用Fresco加载图片，可自行替换自己的图片加载框架

                SimpleDraweeView draweeView = (SimpleDraweeView) view;
                BannerEntity listBean = ((BannerEntity) model);
                draweeView.setImageURI(Uri.parse(listBean.getUrl()));

            }
        });

        //初始化fragment
        initFragment();


        mPresenter.getBanner();
        mPresenter.getMessageRecommendPage();

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshLayout.setRefreshing(true);
                mPresenter.getBanner();
                mPresenter.getMessageRecommendPage();

                for(Fragment fragment : getChildFragmentManager().getFragments()){
                    FRA_NewsItem newsItem = (FRA_NewsItem) fragment;
                    if(newsItem == currentFragment){
                        newsItem.refreshNews();
                    }else {
                        newsItem.setRefreshOnNextShow();
                    }
                }
            }
        });
    }


    private void initFragment() {

        fraSwim = FRA_NewsItem.newInstance(0);
        fraRecovery = FRA_NewsItem.newInstance(1);
        fraBaby = FRA_NewsItem.newInstance(2);

        setCurrentItem(fraSwim, ITEM_SWIM);

    }

    private void setCurrentItem(Fragment choseFragment, int choseItem) {

        if (currentFragment != null && currentFragment == choseFragment) {//重复选择
            return;
        }

        setChoseItemStyle(choseItem);

        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();

        if (currentFragment != null)
            transaction.hide(currentFragment);

        if (choseFragment.isAdded()) {
            transaction.show(choseFragment);
        } else {
            transaction.add(R.id.fra_frame_layout, choseFragment);
        }
        transaction.commitAllowingStateLoss();

        currentFragment = choseFragment;
    }

    private void setChoseItemStyle(int choseItem) {
        lineNewsSwim.setVisibility(View.INVISIBLE);
        lineNewsRecovery.setVisibility(View.INVISIBLE);
        lineNewsBaby.setVisibility(View.INVISIBLE);
        tvNewsSwim.setSelected(false);
        tvNewsRecovery.setSelected(false);
        tvNewsBaby.setSelected(false);
        tvNewsSwim.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f);
        tvNewsRecovery.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f);
        tvNewsBaby.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f);

        switch (choseItem) {
            case ITEM_RECOVERY:
                lineNewsRecovery.setVisibility(View.VISIBLE);
                lineNewsRecovery.setBackgroundResource(R.color.color_FFB024);
                tvNewsRecovery.setSelected(true);
                tvNewsRecovery.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
                break;
            case ITEM_BABY:
                lineNewsBaby.setVisibility(View.VISIBLE);
                lineNewsBaby.setBackgroundResource(R.color.color_FFB024);
                tvNewsBaby.setSelected(true);
                tvNewsBaby.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
                break;
            default:
                lineNewsSwim.setVisibility(View.VISIBLE);
                lineNewsSwim.setBackgroundResource(R.color.color_FFB024);
                tvNewsSwim.setSelected(true);
                tvNewsSwim.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
        }

    }

    @Override
    public void showException(String msg) {
        CommonUtils.makeEventToast(mContext, msg, false);
        refreshLayout.setRefreshing(false);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fra_consult;
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {

    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }


    @OnClick({ R.id.rl_news_swim,
            R.id.rl_news_recovery, R.id.rl_news_baby})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_news_swim:
                setCurrentItem(fraSwim, ITEM_SWIM);
                break;
            case R.id.rl_news_recovery:
                setCurrentItem(fraRecovery, ITEM_RECOVERY);
                break;
            case R.id.rl_news_baby:
                setCurrentItem(fraBaby, ITEM_BABY);
                break;
        }
    }


    @Override
    public void showBanner(BannerDataEntity entity) {
        refreshLayout.setRefreshing(false);

        ArrayList<BannerEntity> arrayList = new ArrayList<>();
        for (int i = 0; i < entity.getBannerList().size(); i++) {
            BannerEntity bannerEntity = new BannerEntity();
            bannerEntity.setUrl(entity.getBannerList().get(i));
            arrayList.add(bannerEntity);
        }

        mBanner.setBannerData(R.layout.layout_fresco_imageview, arrayList);
    }

    @Override
    public void showMessageRecommend(MessageRecommendEntity entity) {
        refreshLayout.setRefreshing(false);

        if (!ListUtil.isListEmpty(entity.getList())) {
            llRecommend.setVisibility(View.VISIBLE);
            llRecommendItem.removeAllViews();
            for (int i = 0; i < entity.getList().size(); i++) {
                final MessageRecommendEntity.ListBean item = entity.getList().get(i);
                if (i == 0) {
                    tvRe1Title.setText(StringUtil.getString(item.getTitle()));
                    tvRe1Des.setText(StringUtil.getString(item.getContent()));
                    if (!ListUtil.isListEmpty(item.getImageList())) {
                        Glide.with(mContext)
                                .load(item.getImageList().get(0).getImageUrl())
                                .transform(new GlideRoundTransform(mContext))
                                .transition(new DrawableTransitionOptions().crossFade())
                                .placeholder(R.mipmap.ic_serve_default)
                                .error(R.mipmap.ic_serve_default)
                                .into(ivRe1Image);
                    }
                    llRecommendItem1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle mBundle = new Bundle();
                            mBundle.putString("id", item.getId());
                            switch (item.getMessageStyle()) {
                                case "0":
                                case "1":
                                case "2":
                                    readyGo(ACT_NewsDetails.class, mBundle);
                                    break;
                                case "3":
                                    readyGo(ACT_VideoPlaying.class, mBundle);
                                    break;
                            }
                        }
                    });
                } else {
                    addMessageRecommendView(item);
                }
            }
        } else {
            llRecommend.setVisibility(View.GONE);
        }

    }

    private void addMessageRecommendView(final MessageRecommendEntity.ListBean item) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_message_recommend, null);
        TextView tvReTitle = view.findViewById(R.id.tv_re_title);
        tvReTitle.setText(StringUtil.getString(item.getTitle()));
        TextView tvReDes = view.findViewById(R.id.tv_re_des);
        tvReDes.setText(StringUtil.getString(item.getContent()));
        TextView tvReTag = view.findViewById(R.id.tv_re_tag);
        /**
         * 资讯类型：0-婴儿游泳，1-产后康复，2-儿童推拿
         */
        String tag;
        if(item.getMessageClassify().equals("0")){
            tag = "婴儿游泳";
        }else if(item.getMessageClassify().equals("1")){
            tag = "产后康复";
        }else {
            tag = "儿童推拿";
        }
        tvReTag.setText(tag);

        if (!ListUtil.isListEmpty(item.getImageList())) {
            Glide.with(mContext)
                    .load(item.getImageList().get(0).getImageUrl())
                    .transform(new GlideRoundTransform(mContext))
                    .transition(new DrawableTransitionOptions().crossFade())
                    .placeholder(R.mipmap.ic_serve_default)
                    .error(R.mipmap.ic_serve_default)
                    .into((ImageView) view.findViewById(R.id.iv_re_image));
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle mBundle = new Bundle();
                mBundle.putString("id", item.getId());
                switch (item.getMessageStyle()) {
                    case "0":
                    case "1":
                    case "2":
                        readyGo(ACT_NewsDetails.class, mBundle);
                        break;
                    case "3":
                        readyGo(ACT_VideoPlaying.class, mBundle);
                        break;
                }
            }
        });

        llRecommendItem.addView(view);
    }
}
